package com.hzhc.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.entity.RectifyCntr;
import com.hzhc.entity.VehicleReservation;
import com.hzhc.mapper.CntrInfoMapper;
import com.hzhc.mapper.CntrLogMapper;
import com.hzhc.mapper.RectifyCntrMapper;
import com.hzhc.mapper.VehicleReservationMapper;
import com.hzhc.service.RectifyCntrService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.RectifyCntrVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 * 待整改表 服务实现类
 * </p>
 *
 * @author 功不唐捐
 * @since 2024-07-25
 */
@Service
@RequiredArgsConstructor
public class RectifyCntrServiceImpl extends ServiceImpl<RectifyCntrMapper, RectifyCntr> implements RectifyCntrService {
    private final CntrLogMapper cntrLogMapper;
    private final CntrInfoMapper cntrInfoMapper;
    private final VehicleReservationMapper reservationMapper;
    @Override
    public ResultUtil<T> addCntrFile(RectifyCntrVo vo, String upfolder, String accessPath) {
        RectifyCntr rectifyCntr=new RectifyCntr();
        BeanUtils.copyProperties(vo,rectifyCntr);
        int i = baseMapper.insert(rectifyCntr);
//        CntrInfo cntrInfo = cntrInfoMapper.getCntrInfoById(rectifyCntr.getCntrNo());
//        CntrLog cntrLog=new CntrLog();
//        if(cntrInfo!=null){
//            //TODO cntrRemark 待整改原因 备注
//            cntrInfo.setCntrWorkRemark("待整改");
//            BeanUtils.copyProperties(cntrInfo,cntrLog);
//            cntrLog.setCreatetime(LocalDateTime.now());
//            cntrLogMapper.insert(cntrLog);
//        }
//        cntrInfoMapper.updateById(cntrInfo);
        //上传图片
        if(vo.getFile()!=null){
            saveFiles(rectifyCntr,vo.getFile(),upfolder,accessPath);
        }
        //修改车辆预约表 箱A(B) 的待整改状态
        VehicleReservation reservation = reservationMapper.selectById(vo.getVehicleReservationId());

        LambdaUpdateWrapper<VehicleReservation> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(VehicleReservation::getId,vo.getVehicleReservationId());
        if (vo.getCntrNo().equals(reservation.getCntrNo())){//箱A
            wrapper.set(VehicleReservation::getDzgTypeA,1);
        }else if (vo.getCntrNo().equals(reservation.getCntrNoB())){//箱B
            wrapper.set(VehicleReservation::getDzgTypeB,1);
        }
        reservationMapper.update(reservation,wrapper);

        return i>0 ? ResultUtil.ok():ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updateCntrFile(RectifyCntrVo vo, String upfolder, String accessPath) {
        RectifyCntr rectifyCntr=new RectifyCntr();
        BeanUtils.copyProperties(vo,rectifyCntr);
        int i = baseMapper.updateById(rectifyCntr);
        //清楚 箱信息表的 待整改
        //上传图片
        if(vo.getFile()!=null){
            saveFiles(rectifyCntr,vo.getFile(),upfolder,accessPath);
        }
        return i>0 ? ResultUtil.ok():ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> delCntrFile(RectifyCntrVo vo) {
        RectifyCntr rectifyCntr = baseMapper.selectById(vo.getId());
        rectifyCntr.setDisable(1);
        boolean b = updateById(rectifyCntr);
        return b ? ResultUtil.ok():ResultUtil.fail();
    }

    @Override
    public List<RectifyCntrVo> getRectifyCntrList(Page<RectifyCntrVo> page, RectifyCntrVo vo) {
        IPage<RectifyCntrVo> pageList = baseMapper.getRectifyCntrList(page, vo);
        return pageList.getRecords();
    }

    public void saveFiles(RectifyCntr rectifyCntr, MultipartFile files, String upfolder, String accessPath) {
        //设置日期格式
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //当地日期转换
        String dayFormat = LocalDate.now().format(formatters);
        //创建新文件：通过路径和时间
        File folder = new File(upfolder + File.separator + dayFormat);
        //文件是否存在，不存在进行创建。
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //获取文件名
        String regEx1 = "[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        String fileName = files.getOriginalFilename();
        String urlName=(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))+ Pattern.compile(regEx1).matcher(fileName).replaceAll("").trim());
        //设置路径
        String path = folder + File.separator;
        File file = getFileByName(1, path, urlName);
        try {
            // 上传文件到服务器
            files.transferTo(file);
            rectifyCntr.setCntrImg(accessPath.replaceAll("\\*", "") + dayFormat + "/"+urlName);
            baseMapper.updateById(rectifyCntr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private File getFileByName(int count, String path, String fileName) {
        File file = new File(path + fileName);
        if (file.exists()) {
            // 文件名已存在
            String prefix = fileName.substring(0, fileName.lastIndexOf(".")) + "(" + count + ")";
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            file = getFileByName(count + 1, path, prefix + suffixName);
        }
        return file;
    }
}
